package cn.rubintry.bug.hunting.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.room.Room
import androidx.viewbinding.ViewBinding
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import cn.rubintry.bug.common.base.BaseFragment
import cn.rubintry.bug.hunting.R
import cn.rubintry.bug.hunting.adapter.MBannerAdapter
import cn.rubintry.bug.hunting.databinding.FragmentDiscoverBinding
import cn.rubintry.bug.hunting.common.event.MoveToFirstTabEvent
import cn.rubintry.bug.hunting.common.event.NetWorkEvent
import cn.rubintry.bug.hunting.common.extension.paddingTop
import cn.rubintry.bug.hunting.common.http.viewmodel.DiscoverViewModel
import cn.rubintry.bug.hunting.pojo.TagDataModel
import cn.rubintry.bug.hunting.room.AppDatabase
import cn.rubintry.bug.hunting.room.DbManager
import cn.rubintry.bug.hunting.viewpager.TagArticleVpAdapter
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs


/**
 * 发现
 */
class DiscoverFragment() : BaseFragment<FragmentDiscoverBinding>(),
    AppBarLayout.OnOffsetChangedListener {

    private var bannerAdapter: MBannerAdapter ?= null
    private val discoverViewModel : DiscoverViewModel by viewModels<DiscoverViewModel>()

    private var vpAdapter : TagArticleVpAdapter ?= null



    override fun layoutId(): Int {
        return R.layout.fragment_discover
    }


    override fun initView() {
        binding?.mHomeToolbar?.paddingTop(BarUtils.getStatusBarHeight())
        binding?.banner?.setIndicator(CircleIndicator(requireContext()))

        binding?.flexibleExampleAppbar?.addOnOffsetChangedListener(this)
        binding?.flexibleExampleCollapsing?.let {
            val layoutParams = it.layoutParams
            layoutParams.height = ScreenUtils.getScreenWidth() / 8 * 5
        }
        bannerAdapter = MBannerAdapter(mutableListOf())
        binding?.banner?.setAdapter(bannerAdapter)
        binding?.banner?.setLoopTime(10000)
        binding?.vpArticle?.offscreenPageLimit = 10000

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        discoverViewModel.getTags()
        discoverViewModel.getBannerImage()
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }
        CoroutineScope(Dispatchers.IO).launch {
            //如果网络不可用，则从本地数据库中获取数据
            if(!NetworkUtils.isAvailable()){
                CoroutineScope(Dispatchers.Main).launch {
                    val cacheTagData = DbManager.getInstance().getDatabase().tagDao().selectAll()
                    val cacheBackgroundData = DbManager.getInstance().getDatabase().homeBackgroundDao().selectAll()
                    if(cacheTagData.isNotEmpty()){
                        updateView(cacheTagData)
                        bannerAdapter?.setDatas(cacheBackgroundData)
                    }
                }
            }

        }

        NetworkUtils.registerNetworkStatusChangedListener(object :
            NetworkUtils.OnNetworkStatusChangedListener {
            override fun onDisconnected() {
                EventBus.getDefault().post(NetWorkEvent(false))
            }

            override fun onConnected(networkType: NetworkUtils.NetworkType?) {
                EventBus.getDefault().post(NetWorkEvent(true))
            }
        })
    }

    override fun observeData() {
        discoverViewModel.tagData.observe(this){data ->
            if(data.code == "0"){
                data?.data?.let {
                    DbManager.getInstance().getDatabase().tagDao().insert(*data.data.toTypedArray())
                    updateView(data.data)
                }
            }else{
                ToastUtils.showShort("请求失败：" + data.message)
            }
        }

        discoverViewModel.bannerData.observe(this){ data ->
            if (data.code == "0") {
                data?.data?.let {
                    DbManager.getInstance().getDatabase().homeBackgroundDao().insert(*data.data.toTypedArray())
                    bannerAdapter?.setDatas(data.data)
                }
            }
        }
    }

    private fun updateView(data: List<TagDataModel>) {

        vpAdapter = TagArticleVpAdapter(data , childFragmentManager , lifecycle)
        binding?.vpArticle?.adapter = vpAdapter
        // 将TabLayout与ViewPager2同步
        TabLayoutMediator(
            binding?.tbArticleTags!!, binding?.vpArticle!!
        ) { tab, position ->
            tab.setText(data[position].tagName)
        }.attach()
    }


    override fun bindingClazz(): Class<out ViewBinding> {
        return FragmentDiscoverBinding::class.java
    }

    override fun onNetWorkError(msg: String) {

    }

    override fun onDestroy() {
        super.onDestroy()
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

    override fun onOffsetChanged(appBarLayout: AppBarLayout, i: Int) {
        val alpha = abs(i).toFloat() / appBarLayout.totalScrollRange
        binding?.line?.visibility = if(alpha == 1f){
            View.GONE
        }else{
            View.VISIBLE
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun moveTabToFirst(event: MoveToFirstTabEvent){
        binding?.tbArticleTags?.getTabAt(0)?.select()
    }


}